package com.bjpowernode.controller;

import com.bjpowernode.pojo.ProductInfo;
import com.bjpowernode.pojo.vo.ProductInfoVo;
import com.bjpowernode.service.ProductInfoService;
import com.bjpowernode.utils.FileNameUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.support.SimpleTriggerContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/prod")
public class ProductInfoAction {
    //每页显示的记录数
    public static final int PAGE_SIZE = 5;
    //异步上传图片的名称
    String saveFileName = "";

    @Autowired
    ProductInfoService productInfoService;

    @RequestMapping("/getAll")
    public String getAll(HttpServletRequest request) {
        List<ProductInfo> list = productInfoService.getAll();
        request.setAttribute("list", list);
        return "product";
    }

    //显示第一页的第五条记录
    @RequestMapping("/split")
    public String split(HttpServletRequest request) {
        PageInfo info =null;
        Object vo = request.getSession().getAttribute("prodVo");
        if(vo!=null){
            info = productInfoService.splitPageVo((ProductInfoVo) vo, PAGE_SIZE);
            request.getSession().removeAttribute("prodVo");
        }else {
            //得到第一页的数据
            info = productInfoService.splitPage(1, PAGE_SIZE);
        }
        request.setAttribute("info", info);
        return "product";
    }


    //ajax分页处理
    @ResponseBody
    @RequestMapping("/ajaxsplit")
    public void ajaxsplit(ProductInfoVo vo, HttpSession Session) {
        PageInfo info = productInfoService.splitPageVo(vo,PAGE_SIZE);
        //session封装页面数据进info是因为查询完后要进行页面数据的更新
        Session.setAttribute("info", info);

    }
    //    多条件查询
    @ResponseBody
    @RequestMapping("/condition")
    public void condition(ProductInfoVo vo,HttpSession session){
        List<ProductInfo> list = productInfoService.selectCondition(vo);
        session.setAttribute("tplist",list);
    }

    //    异步ajax文件上传
    @RequestMapping("ajaxImg")
    @ResponseBody
    public Object ajaxImg(MultipartFile pimage, HttpServletRequest request) {
        //    提取生成的文件名UUID+上传文件的后缀.png,jpg...
        saveFileName = FileNameUtil.getUUIDFileName() + FileNameUtil.getFileType(pimage.getOriginalFilename());
        //    获取项目中图片存储路径（把图片放在哪里）F:\java——note\mimissm\src\main\webapp\image_big
        String path = request.getServletContext().getRealPath("/image_big");
        System.out.println("异步ajax图片的路径=========》" + path);
        //    转存(F:\java——note\mimissm\src\main\webapp\image_big+/+saveFileName
        try {
            pimage.transferTo(new File(path + File.separator + saveFileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回客户端json对象，封装图片路径，实现立即回显
        JSONObject obj = new JSONObject();
        obj.put("imgurl", saveFileName);
        return obj.toString();
    }

    @RequestMapping("/save")
    public String save(ProductInfo info, HttpServletRequest request) {
        info.setpImage(saveFileName);
        info.setpDate(new Date());
        //    info里已经封装了表单里的所有信息
        int num = -1;
        try {
            num = productInfoService.save(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0) {
            request.setAttribute("msg", "增加成功");
        } else {
            request.setAttribute("msg", "增加失败");
        }
        //    清空saveFileName，方便下次异步ajax进行增加或修改的操作
        saveFileName = "";
        //增加成功后应该重新访问数据库，跳转到分页显示页面即转发到分页显示的请求
        return "forward:/prod/split.action";
    }

    //    根据主键查询商品
    @RequestMapping("/one")
    public String one(int pid,ProductInfoVo vo, Model model,HttpSession session) {
        ProductInfo info = productInfoService.getById(pid);
        //将多条件及页码放入session中，更新处理结束后分页时，读取条件和页码进行处理
        session.setAttribute("prodVo",vo );
        model.addAttribute("prod", info);
        return "update";
    }

    //更新商品
    @RequestMapping("/update")
    public String update(ProductInfo info, HttpServletRequest request) {
        // ajax异步图片上传。如果上传过则savefilename里有图片的名称
        //         如果没有上传过则savefilename="",
        //    若为空则实体类info使用隐藏表单域提供上来的pImage原始图片的名称
        if (!saveFileName.equals("")) {
            info.setpImage(saveFileName);
        }
        int num = -1;
        try {
            num = productInfoService.update(info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0) {
            request.setAttribute("msg", "更新成功");
        } else {
            request.setAttribute("msg", "更新失败");
        }
//清空savefilename
        saveFileName = "";
        return "forward:/prod/split.action";
    }

    //    删除单个商品
    @RequestMapping("/delete")
    public String deleate(int pid,ProductInfoVo vo, HttpServletRequest request) {
        ProductInfo byId = productInfoService.getById(pid);
        String s = byId.getpName();

        int num = -1;
        try {
            num = productInfoService.delete(pid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (num > 0) {
            request.setAttribute("msg", "删除" + s + "成功");
            request.getSession().setAttribute("deleteProdVo",vo );
        } else {
            request.setAttribute("msg", "删除" + s + "失败");
        }

        //删除成功后跳转到分页显示
        return "forward:/prod/deleteAjaxSplit.action";
    }

    //    删除跳转到分页显示的ajax,是前端ajax的回调函数
    @ResponseBody
    @RequestMapping(value = "/deleteAjaxSplit", produces = "text/html;charset=UTF-8")
    public Object deleateAjaxSplit(HttpServletRequest request) {
        System.out.println("跳转到product/deleteAjaxSplit请求");
        PageInfo info =null;
        // 取得第一页的数据
        Object vo = request.getSession().getAttribute("deleteProdVo");
        if(vo!=null){
             info = productInfoService.splitPageVo((ProductInfoVo) vo, PAGE_SIZE);
        }else {
            info = productInfoService.splitPage(1, PAGE_SIZE);
        }
        //将数据放在session域中以便ajax请求回调函数进行页面刷新
        request.getSession().setAttribute("info", info);

        return request.getAttribute("msg");
    }

    //    批量删除
    @RequestMapping("/deleteBatch")
    public String deleteBatch(String pids, HttpServletRequest request) {
        // 将前端传送过来的pids（1，2，3）转化成[1,2,3]
        String ps[] = pids.split(",");
        int num = -1;

        try {
            num = productInfoService.deleteBatch(ps);
            if(num>0){
               request.setAttribute("msg", "批量删除成功");
            }else {
                request.setAttribute("msg","批量删除失败" );
            }
        } catch (Exception e) {
            request.setAttribute("msg","当前商品不可删除" );
        }
        //批量删除后通过ajax重新进行分页，返回客户端
        return "forward:/prod/deleteAjaxSplit.action";
    }




}
